package org.hcyspartnoc.demo.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.time.Instant;

public class BaiFileUtils {
    public static void deleteFilesOlderThan(String dirPath, Duration duration) {
        try {
            Path directory = Paths.get(dirPath);
            // 获取当前时间
            Instant now = Instant.now();
            // 遍历目录中的所有文件和子目录
            Files.walk(directory)
                    .filter(path -> !Files.isDirectory(path)) // 过滤出文件
                    .forEach(path -> {
                        try {
                            // 获取文件的最后修改时间
                            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
                            Instant lastModifiedTime = attrs.lastModifiedTime().toInstant();

                            // 检查文件是否早于指定时间
                            if (Duration.between(lastModifiedTime, now).compareTo(duration) > 0) {
                                // 删除文件
                                Files.delete(path);
                                System.out.println("Deleted: " + path);
                            }
                        } catch (IOException e) {
                            System.err.println("Error processing file: " + path + ". " + e.getMessage());
                        }
                    });
        } catch (Exception ignore) {
        }

    }
}
